import json
import datetime
from django.http import HttpResponse
from django.shortcuts import render
import os
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "green.settings")
django.setup()

# render请求
from green import models


city = ['北京', '天津', '河北', '山西', '内蒙古', '辽宁', '吉林', '黑龙江', '上海', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '广西']

def one(request):
    return render(request, "one/one.html")


def showOne(request):
    year = request.GET.get('year')
    month = request.GET.get('month')
    print(year, month)
    date = str(year) + "/" + str(month)

    f = open('../../templates/one/bigJson.json', 'r', encoding='utf-8')
    bigJson = f.read()
    f.close()
    bigDict = json.loads(bigJson)
    data = bigDict[date]

    person = {"data": data}
    response = HttpResponse(json.dumps(person), content_type='application/json; charset=utf-8')
    return response


def initBigJsonForOne():
    monthList = [str(Y) + '/' + str(M) for Y in range(2019, 2021) for M in range(1, 13)]
    monthList = monthList[:-1]
    print(monthList)
    bigJson = {}
    for oneMonth in monthList:

        tempList = []
        date = datetime.date(int(oneMonth.split("/", 1)[0]), int(oneMonth.split("/", 1)[1]), 1)
        while date.month == int(oneMonth.split("/", 1)[1]):
            # 日期还在这个月内
            queryDate = str(date.year) + "/" + str(date.month) + "/" + str(date.day)
            print(queryDate)
            thisMonthData = models.Chinaco2.objects.filter(date=date).values("co2")[0]

            print(thisMonthData["co2"])
            tempList.append({'date': str(date.day), 'num': thisMonthData["co2"]})
            print(tempList)

            # 处理完成，换下一天
            date = date + datetime.timedelta(days=1)
        bigJson[oneMonth] = tempList

    # 将bigJson保存为文件

    s = json.dumps(bigJson)
    f = open('../../templates/one/bigJson.json', 'w', encoding='UTF-8')
    f.write(s)
    f.close()
    print("构造bigJson.json成功！")
    return HttpResponse("构造成功！")


if __name__ == '__main__':
    initBigJsonForOne()
